/*
 * broadcaster.cpp
 *
 *  Created on: Aug 28, 2010
 *      Author: kevin
 */

#include "broadcaster.h"
#include <iostream>
#include <sstream>
using namespace std;

#include <Poco/DOM/Element.h>
#include <Poco/DOM/DOMWriter.h>
#include <Poco/DOM/Document.h>
using Poco::XML::Element;
using Poco::XML::DOMWriter;
using Poco::XML::Document;

Broadcaster::Broadcaster(SocketAddress address, string name):
	_sock(new MulticastSocket),
	_name(name)
{
	cout << "Broadcaster :: Constructing Broadcaster on :: " << _sock->address().toString() << endl;
	_sock->bind(SocketAddress("234.42.35.70", 0));
	cout << "Broadcaster :: Bound address" << endl;
	_sock->joinGroup(_sock->address().host());
	cout << "Broadcaster :: Joined group" << endl;

}

Broadcaster::~Broadcaster()
{
	cout << "Broadcaster :: Destructing Broadcaster" << endl;
}

void Broadcaster::run(){
	Timer timer(2000,2000);
	timer.start(TimerCallback<Broadcaster>(*this, &Broadcaster::onTimer), Poco::Thread::PRIO_HIGHEST);
	while(true){
	}
}

void Broadcaster::send(){
	//cout << "Broadcaster :: Sending name :: " << _name << " from :: " << _sock->address().toString() << endl;
	string name = "cecilia";
	Document* doc = new Document();
	Element* ring = doc->createElement("ring");
	ring->setAttribute("name",name);
	doc->appendChild(ring);
	ostringstream out;
	DOMWriter w;
	out.flush();
	w.writeNode(out, doc);
	_sock->sendTo(out.str().c_str(), out.str().size(), SocketAddress("234.42.35.70",42069));
}

void Broadcaster::setName(string name){
	_name = name;
}

void Broadcaster::onTimer(Timer &timer){
	send();
}
